<template>
  <div class="merchant-settlement">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>待结算总额</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">¥{{ statistics.pendingAmount }}</div>
            <div class="trend">
              较上月
              <span :class="statistics.pendingTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(statistics.pendingTrend) }}%
                <el-icon>
                  <component :is="statistics.pendingTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>本月结算总额</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">¥{{ statistics.monthlyAmount }}</div>
            <div class="trend">
              较上月
              <span :class="statistics.monthlyTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(statistics.monthlyTrend) }}%
                <el-icon>
                  <component :is="statistics.monthlyTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>待处理申请</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ statistics.pendingCount }}</div>
            <div class="percentage">
              占比 {{ statistics.pendingPercentage }}%
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>结算周期</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ getSettlementCycleText(statistics.settlementCycle) }}</div>
            <el-button type="primary" link @click="handleSettlementCycle">
              修改周期
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="商家名称">
          <el-input v-model="searchForm.name" placeholder="请输入商家名称" clearable />
        </el-form-item>
        <el-form-item label="结算状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待结算" value="pending" />
            <el-option label="已结算" value="settled" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleExportReport">
            <el-icon><Download /></el-icon>导出报表
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>结算申请列表</span>
          <el-button type="primary" @click="handleAdd">发起结算</el-button>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="merchantName" label="商家名称" min-width="150" />
        <el-table-column prop="amount" label="结算金额" width="120">
          <template #default="{ row }">
            ¥{{ row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="bankName" label="开户银行" width="150" />
        <el-table-column prop="bankAccount" label="银行账号" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="申请时间" width="180" />
        <el-table-column prop="settleTime" label="结算时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 'pending'"
              type="primary"
              link
              @click="handleSettle(row)"
            >
              结算
            </el-button>
            <el-button type="primary" link @click="handleView(row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 发起结算对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="发起结算"
      width="500px"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addRules"
        label-width="100px"
      >
        <el-form-item label="商家" prop="merchantId">
          <el-select
            v-model="addForm.merchantId"
            placeholder="请选择商家"
            filterable
            remote
            :remote-method="searchMerchants"
            :loading="merchantLoading"
          >
            <el-option
              v-for="item in merchantOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="结算金额" prop="amount">
          <el-input-number
            v-model="addForm.amount"
            :min="0"
            :precision="2"
            :step="100"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="开户银行" prop="bankName">
          <el-input v-model="addForm.bankName" placeholder="请输入开户银行" />
        </el-form-item>
        <el-form-item label="银行账号" prop="bankAccount">
          <el-input v-model="addForm.bankAccount" placeholder="请输入银行账号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="addForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 结算对话框 -->
    <el-dialog
      v-model="settleDialogVisible"
      title="确认结算"
      width="500px"
    >
      <el-form
        ref="settleFormRef"
        :model="settleForm"
        :rules="settleRules"
        label-width="100px"
      >
        <el-form-item label="结算金额">
          <span>¥{{ settleForm.amount.toFixed(2) }}</span>
        </el-form-item>
        <el-form-item label="开户银行">
          <span>{{ settleForm.bankName }}</span>
        </el-form-item>
        <el-form-item label="银行账号">
          <span>{{ settleForm.bankAccount }}</span>
        </el-form-item>
        <el-form-item label="结算备注" prop="remark">
          <el-input
            v-model="settleForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入结算备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="settleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSettleSubmit">确认结算</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="结算详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="商家名称">{{ detail.merchantName }}</el-descriptions-item>
        <el-descriptions-item label="结算金额">
          ¥{{ detail.amount?.toFixed(2) }}
        </el-descriptions-item>
        <el-descriptions-item label="开户银行">{{ detail.bankName }}</el-descriptions-item>
        <el-descriptions-item label="银行账号">{{ detail.bankAccount }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ detail.createTime }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(detail.status)">
            {{ getStatusText(detail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item
          v-if="detail.status !== 'pending'"
          label="结算时间"
        >
          {{ detail.settleTime }}
        </el-descriptions-item>
        <el-descriptions-item
          v-if="detail.status === 'rejected'"
          label="拒绝原因"
        >
          {{ detail.rejectReason }}
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">
          {{ detail.remark }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 结算周期设置对话框 -->
    <el-dialog
      v-model="cycleDialogVisible"
      title="结算周期设置"
      width="500px"
    >
      <el-form
        ref="cycleFormRef"
        :model="cycleForm"
        :rules="cycleRules"
        label-width="120px"
      >
        <el-form-item label="结算周期" prop="cycle">
          <el-select v-model="cycleForm.cycle" placeholder="请选择结算周期">
            <el-option label="每日结算" value="daily" />
            <el-option label="每周结算" value="weekly" />
            <el-option label="每月结算" value="monthly" />
            <el-option label="自定义" value="custom" />
          </el-select>
        </el-form-item>
        <el-form-item 
          v-if="cycleForm.cycle === 'custom'"
          label="结算间隔(天)" 
          prop="interval"
        >
          <el-input-number 
            v-model="cycleForm.interval" 
            :min="1" 
            :max="30"
          />
        </el-form-item>
        <el-form-item 
          v-if="cycleForm.cycle === 'weekly'"
          label="结算日" 
          prop="settlementDay"
        >
          <el-select v-model="cycleForm.settlementDay" placeholder="请选择结算日">
            <el-option label="周一" value="1" />
            <el-option label="周二" value="2" />
            <el-option label="周三" value="3" />
            <el-option label="周四" value="4" />
            <el-option label="周五" value="5" />
            <el-option label="周六" value="6" />
            <el-option label="周日" value="7" />
          </el-select>
        </el-form-item>
        <el-form-item 
          v-if="cycleForm.cycle === 'monthly'"
          label="结算日" 
          prop="settlementDay"
        >
          <el-input-number 
            v-model="cycleForm.settlementDay" 
            :min="1" 
            :max="28"
            placeholder="每月几号结算"
          />
        </el-form-item>
        <el-form-item label="结算时间" prop="settlementTime">
          <el-time-picker
            v-model="cycleForm.settlementTime"
            format="HH:mm"
            placeholder="选择时间"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="cycleForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cycleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCycleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 报表导出对话框 -->
    <el-dialog
      v-model="exportDialogVisible"
      title="导出结算报表"
      width="500px"
    >
      <el-form
        ref="exportFormRef"
        :model="exportForm"
        :rules="exportRules"
        label-width="120px"
      >
        <el-form-item label="报表类型" prop="type">
          <el-select v-model="exportForm.type" placeholder="请选择报表类型">
            <el-option label="结算汇总报表" value="summary" />
            <el-option label="结算明细报表" value="detail" />
            <el-option label="结算趋势报表" value="trend" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围" prop="dateRange">
          <el-date-picker
            v-model="exportForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结算状态" prop="status">
          <el-select v-model="exportForm.status" placeholder="请选择状态" multiple>
            <el-option label="待结算" value="pending" />
            <el-option label="已结算" value="settled" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item label="导出格式" prop="format">
          <el-radio-group v-model="exportForm.format">
            <el-radio label="excel">Excel</el-radio>
            <el-radio label="pdf">PDF</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="exportDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleExportSubmit" :loading="exportLoading">
            确认导出
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download } from '@element-plus/icons-vue'
import {
  getMerchantSettlementList,
  submitMerchantSettlement,
  handleMerchantSettlement,
  getMerchantList,
  getMerchantSettlementStatistics,
  updateMerchantSettlementCycle,
  exportMerchantSettlementReport
} from '@/api/merchant'

// 搜索表单
const searchForm = reactive({
  name: '',
  status: '',
  dateRange: []
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 发起结算对话框
const addDialogVisible = ref(false)
const addFormRef = ref(null)
const addForm = reactive({
  merchantId: '',
  amount: 0,
  bankName: '',
  bankAccount: '',
  remark: ''
})

// 结算对话框
const settleDialogVisible = ref(false)
const settleFormRef = ref(null)
const settleForm = reactive({
  id: '',
  amount: 0,
  bankName: '',
  bankAccount: '',
  remark: ''
})

// 详情对话框
const detailVisible = ref(false)
const detail = reactive({})

// 商家选择
const merchantLoading = ref(false)
const merchantOptions = ref([])

// 统计数据
const statistics = ref({
  pendingAmount: 0,
  pendingTrend: 0,
  monthlyAmount: 0,
  monthlyTrend: 0,
  pendingCount: 0,
  pendingPercentage: 0,
  settlementCycle: 'monthly'
})

// 结算周期设置
const cycleDialogVisible = ref(false)
const cycleFormRef = ref(null)
const cycleForm = reactive({
  cycle: '',
  interval: 7,
  settlementDay: '',
  settlementTime: '',
  remark: ''
})

const cycleRules = {
  cycle: [{ required: true, message: '请选择结算周期', trigger: 'change' }],
  interval: [{ required: true, message: '请输入结算间隔', trigger: 'blur' }],
  settlementDay: [{ required: true, message: '请选择结算日', trigger: 'change' }],
  settlementTime: [{ required: true, message: '请选择结算时间', trigger: 'change' }]
}

// 报表导出
const exportDialogVisible = ref(false)
const exportFormRef = ref(null)
const exportLoading = ref(false)
const exportForm = reactive({
  type: 'summary',
  dateRange: [],
  status: [],
  format: 'excel'
})

const exportRules = {
  type: [{ required: true, message: '请选择报表类型', trigger: 'change' }],
  dateRange: [{ required: true, message: '请选择时间范围', trigger: 'change' }],
  status: [{ required: true, message: '请选择结算状态', trigger: 'change' }],
  format: [{ required: true, message: '请选择导出格式', trigger: 'change' }]
}

// 表单验证规则
const addRules = {
  merchantId: [
    { required: true, message: '请选择商家', trigger: 'change' }
  ],
  amount: [
    { required: true, message: '请输入结算金额', trigger: 'blur' }
  ],
  bankName: [
    { required: true, message: '请输入开户银行', trigger: 'blur' }
  ],
  bankAccount: [
    { required: true, message: '请输入银行账号', trigger: 'blur' },
    { pattern: /^\d{16,19}$/, message: '请输入正确的银行账号', trigger: 'blur' }
  ]
}

const settleRules = {
  remark: [
    { required: true, message: '请输入结算备注', trigger: 'blur' },
    { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
  ]
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    pending: 'warning',
    settled: 'success',
    rejected: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待结算',
    settled: '已结算',
    rejected: '已拒绝'
  }
  return statusMap[status] || '未知'
}

// 获取列表数据
const getList = async () => {
  loading.value = true
  try {
    const { data } = await getMerchantSettlementList({
      page: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1]
    })
    tableData.value = data.list
    total.value = data.total
  } catch (error) {
    ElMessage.error('获取结算申请列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索商家
const searchMerchants = async (query) => {
  if (query) {
    merchantLoading.value = true
    try {
      const { data } = await getMerchantList({
        name: query,
        page: 1,
        pageSize: 10
      })
      merchantOptions.value = data.list
    } catch (error) {
      ElMessage.error('搜索商家失败')
    } finally {
      merchantLoading.value = false
    }
  } else {
    merchantOptions.value = []
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  searchForm.dateRange = []
  handleSearch()
}

// 发起结算
const handleAdd = () => {
  addForm.merchantId = ''
  addForm.amount = 0
  addForm.bankName = ''
  addForm.bankAccount = ''
  addForm.remark = ''
  addDialogVisible.value = true
}

// 提交结算申请
const handleAddSubmit = async () => {
  if (!addFormRef.value) return
  await addFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await submitMerchantSettlement(addForm)
        ElMessage.success('提交结算申请成功')
        addDialogVisible.value = false
        getList()
      } catch (error) {
        ElMessage.error('提交结算申请失败')
      }
    }
  })
}

// 结算
const handleSettle = (row) => {
  settleForm.id = row.id
  settleForm.amount = row.amount
  settleForm.bankName = row.bankName
  settleForm.bankAccount = row.bankAccount
  settleForm.remark = ''
  settleDialogVisible.value = true
}

// 提交结算
const handleSettleSubmit = async () => {
  if (!settleFormRef.value) return
  await settleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await handleMerchantSettlement(settleForm.id, {
          remark: settleForm.remark
        })
        ElMessage.success('结算成功')
        settleDialogVisible.value = false
        getList()
      } catch (error) {
        ElMessage.error('结算失败')
      }
    }
  })
}

// 查看详情
const handleView = (row) => {
  Object.assign(detail, row)
  detailVisible.value = true
}

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getList()
}

// 获取结算周期文本
const getSettlementCycleText = (cycle) => {
  const cycleMap = {
    daily: '每日结算',
    weekly: '每周结算',
    monthly: '每月结算',
    custom: '自定义结算'
  }
  return cycleMap[cycle] || cycle
}

// 处理结算周期设置
const handleSettlementCycle = () => {
  cycleForm.cycle = statistics.value.settlementCycle
  cycleDialogVisible.value = true
}

// 提交结算周期设置
const handleCycleSubmit = async () => {
  if (!cycleFormRef.value) return
  await cycleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await updateMerchantSettlementCycle(cycleForm)
        ElMessage.success('结算周期设置成功')
        cycleDialogVisible.value = false
        // 刷新统计数据
        fetchStatistics()
      } catch (error) {
        ElMessage.error('结算周期设置失败')
      }
    }
  })
}

// 处理导出报表
const handleExportReport = () => {
  exportDialogVisible.value = true
}

// 提交导出报表
const handleExportSubmit = async () => {
  if (!exportFormRef.value) return
  await exportFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        exportLoading.value = true
        const res = await exportMerchantSettlementReport(exportForm)
        // 处理文件下载
        const blob = new Blob([res], { type: 'application/octet-stream' })
        const link = document.createElement('a')
        link.href = window.URL.createObjectURL(blob)
        link.download = `结算报表_${exportForm.type}_${exportForm.dateRange[0]}_${exportForm.dateRange[1]}.${exportForm.format}`
        link.click()
        window.URL.revokeObjectURL(link.href)
        ElMessage.success('报表导出成功')
        exportDialogVisible.value = false
      } catch (error) {
        ElMessage.error('报表导出失败')
      } finally {
        exportLoading.value = false
      }
    }
  })
}

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const res = await getMerchantSettlementStatistics()
    statistics.value = res.data
  } catch (error) {
    ElMessage.error('获取统计数据失败')
  }
}

onMounted(() => {
  getList()
  fetchStatistics()
})
</script>

<style lang="scss" scoped>
.merchant-settlement {
  padding: 20px;

  .statistics-cards {
    margin-bottom: 20px;
    
    .card-content {
      text-align: center;
      
      .amount {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        margin-bottom: 8px;
        
        &.warning {
          color: #E6A23C;
        }
      }
      
      .trend {
        font-size: 14px;
        color: #909399;
        
        .up {
          color: #67C23A;
        }
        
        .down {
          color: #F56C6C;
        }
      }
      
      .percentage {
        font-size: 14px;
        color: #909399;
      }
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}
</style> 